package com.situ.Servlet.Test;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取时间，通过cookie打印出上次登陆时间
 * @author 18234
 *
 */
public class ListTimeServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取时间设置到cookie上
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String time = simpleDateFormat.format(date);//获取时间
		Cookie cookie = new Cookie("lastTime", time);
		resp.addCookie(cookie);
		
		//获取cookie的时间
		String lastTime = null;
		Cookie[] cookies = req.getCookies();
		if (cookie != null) {
			for (Cookie cook : cookies) {
				if (cook.getName().equals("lastTime")) {
					lastTime = cook.getValue();
					System.out.println(lastTime);//看控制台有没有
				}
			}
		}
		
		//cookie浏览器显示
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		if (lastTime == null) {
			writer.println("第一次访问");
		}else {
			writer.print("上次访问的时间： " + lastTime);
		}
	}
	
}
